<template>
    <header class="pb-2 flex items-center justify-between pt-2">
      <aside class="flex items-center w-2/5">
        <n-button type="success" @click="addUser">添加客户</n-button>
        <n-date-picker 
         clearable 
         v-model:value="timestamp"
         type="date" 
         class="w-2/5 mx-4"
         size="large"
        />
        <n-button type="info">日期查询</n-button>
      </aside>
      <aside>
        <n-button strong secondary type="success" @click="exportCsv">导出csv</n-button>
      </aside>
    </header>
    <n-data-table 
        striped 
        bordered 
        ref="tableRef"
        :columns="columns"
        :data="commentList"
        :pagination="pagination"
        @update:sorter="handleUpdateSorter"
      />


    <!-- 添加客户 -->
    <n-modal
      v-model:show="showModal"
      preset="dialog"
      title="添加用户"
  >
    <n-form
      ref="addUserFormRef"
      :model="addUserForm"
      :rules="rules"
    >
    <n-form-item label="用户名" 
      path="username" 
    >
      <n-input v-model:value="addUserForm.username" placeholder="请输入用户名" />
    </n-form-item>
    <n-form-item label="手机号" path="phone">
      <n-input v-model:value="addUserForm.phone" placeholder="请输入手机号" />
    </n-form-item>
    <n-form-item label="留言内容" path="comment_content">
      <n-input v-model:value="addUserForm.comment_content" placeholder="请输入留言内容" />
    </n-form-item>
    <n-form-item label="地址" path="address">
      <n-input v-model:value="addUserForm.address" placeholder="请输入地址" />
    </n-form-item>
    <n-form-item label="邮箱" path="email">
      <n-input v-model:value="addUserForm.email" placeholder="请输入邮箱" />
    </n-form-item>
    <n-form-item class="flex justify-end">
      <n-button type="error" class="mx-3" @click="cancelCallback">取消</n-button>
      <n-button type="success" @click="submitCallback">确定</n-button>
    </n-form-item>
    </n-form>
    </n-modal>
 </template>
 
 <script lang="ts" setup>
     import { reactive,ref } from 'vue'
     import { h } from 'vue'
     import { NButton, NDataTable, NPopconfirm, NSwitch } from 'naive-ui'
     import { getCurrentInstance } from 'vue';
     import { onMounted } from 'vue';
     import type { FormItemRule } from 'naive-ui'
      import dayjs from 'dayjs';
     let { proxy } = getCurrentInstance()
     let timestamp = ref()

    /**
     * 获取数据源
     */
    const columns = [
      {
        title: '编号',
        key: 'id',
        width: 70
      },
      {
        title: '用户名',
        key: 'username',
        width: 80
      },
      {
        title: '手机号',
        key: 'phone'
      },
      {
        title: "留言内容",
        key: "comment_content",
        width: 350,
        ellipsis: {
          tooltip: true
        }
      },
      {
        title: "邮箱",
        key: "email"
      },
      {
        title: '地址',
        key: 'address'
      },
      {
        title: "是否联系",
        key: 'is_contact',
        render: (row) => {
          return h(NSwitch, {
            value: row.is_contact,
            onUpdateValue: async (value) => {
              let id:number = row.id // 用户留言编号
              let res = await proxy.$http.put(`/user/${id}`, {status: value})
                if (res.data.code !== 200) return proxy.$message.error("修改失败")
                proxy.$message.success("修改成功")
            }
          })
        }
      },
      {
        title: '留言时间',
        key: "createdAt",
        sortOrder: true,
        sorter: (a, b) => dayjs(a.createdAt).valueOf() - dayjs(b.createdAt).valueOf(),
        render: (row) => {
          return dayjs(row.createdAt).format('YYYY-MM-DD HH:mm:ss')
        }
      },
      {
          title: '操作',
          key: 'tags',
          width: 200,
          
          render(row) {
            return h('div',{
              style: { display: 'flex', justifyContent: 'center' }
            },
              [
                h(NPopconfirm, {
              onPositiveClick: async () => {
                let id:number = row.id // 用户留言编号
                let { data: res } = await proxy.$http.delete(`/user/deleteComment/${id}`).then(res => {
                  console.log(res)
                  if (res.data.code === 200) {
                    proxy.$message.success("删除成功")
                    getInfoList()
                  } else {
                    proxy.$message.error("删除失败")
                  }
                })
              },
              onNegativeClick: () => {
                proxy.$message.info("取消删除")
              }
            }, 
            {
              trigger: () => h(NButton, { type: 'error' }, '删除'),
              default: () => h(
              'div', 
              '确定删除吗？',
            )
            }),
            h(NButton, {
              type: 'success',
              style: { marginLeft: '10px' },
              onClick: () => {
                proxy.$dialog.success({
                  title: '查看留言',
                  content: row.comment_content
               })
              }
            },{default: () => h('span', '查看')})
          ]
            )
          }
        }
      ]
      onMounted(() => {
        getInfoList()
      })
      const commentList = ref([])
        // 获取数据
       let getInfoList = async () => {
            let {data:res} = await proxy.$http.get('/user/getComment')
            commentList.value = res.data
        }
        const pagination = reactive({
          page: 1,
          pageSize: 10,
          showSizePicker: true,
          pageSizes: [10, 15, 20],
          onChange: (page: number) => {
            pagination.page = page
          },
          onUpdatePageSize: (pageSize: number) => {
            pagination.pageSize = pageSize
            pagination.page = 1
          }
    })
        let tableRef = ref()
        // 导出csv
        const exportCsv = () => {
          tableRef.value?.downloadCsv({
            filename: "data-table",
            keepOriginalData: true
          })
        }
      /*
      * 添加客户
      */ 
      let showModal = ref(false)
      // 添加用户的信息
      let addUserForm = reactive({
        username: "",
        phone: "",
        email: "",
        comment_content: "",
        address: ""
      })
      let addUserFormRef = ref()
      let rules = reactive({
        username: [
          {
            required: true,
            validator(rule: FormItemRule, value: string) {
              if (!value) {
                return new Error('用户名不能为空')
              } else if(value.length <= 2) {
                return new Error('用户名最少为2位')
              } else {
                return true
              }
            },
            trigger: ['input','blur']
          }
        ],
        phone: {
          required: true,
          validator(rule: FormItemRule, value: string) {
            if (!value) {
              return new Error('手机号不能为空')
            } else if(!/^1[3-9]\d{9}/.test(value)) {
              return new Error('手机号格式不正确')
            } else {
              return true
            }
          },
          trigger: ['input','blur']
        },
        comment_content: [
          {
            required: true,
            message: '请输入留言内容',
            trigger: ['input','blur']
          }
        ],
        email: {
          required: true,
          validator(rule: FormItemRule, value: string) {
            if (!value) {
              return new Error('邮箱不能为空')
            } else if(!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
              return new Error('邮箱格式不正确')
            }
          },
          trigger: ['input','blur']
        },
        address: {
          required: true,
          message: "地址不能为空",
          trigger: ['input','blur']
        }
      })
      // 提交添加回调
      const submitCallback = () => {
        console.log("提交")
        addUserFormRef.value.validate(async (errors:any) => {
          if (!errors) {
            let {data:res} = await proxy.$http.post('/user/addComment',addUserForm)
            if(res.code === 200) {
              proxy.$message.success("添加成功")
              showModal.value = false
              clearFormValue()
              getInfoList()
            } else {
              proxy.$message.error("添加失败")
            }
          }
        })
      }
      const clearFormValue = () => {
        addUserForm.username = ""
        addUserForm.phone = ""
        addUserForm.email = ""
        addUserForm.comment_content = ""
        addUserForm.address = ""
      }
      // 提交取消的会带哦
      const cancelCallback = () => {
        addUserFormRef.value.restoreValidation()
        showModal.value = false
      } 
      let addUser = () => {
        showModal.value = true
      }


 </script>